package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.MapperImpl.LoginMapperImpl;
import com.example.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Controller
public class IndexController {
    @Autowired
    LoginMapperImpl loginMapper;

    @RequestMapping(value = {"/","/home"})
    public String index(){
        return "index";
    }

    @ResponseBody
    @RequestMapping("/api/user/login")
    public String login (@RequestBody String body,HttpServletResponse response) {

        JSONObject parse = JSONObject.parseObject(body);
        String username = (String) parse.get("username");
        String password = (String) parse.get("password");

        User user = loginMapper.queryUserByName(username);

        HashMap<String,Object> res = new HashMap<>();
        HashMap<String,Object> data = new HashMap<>();
        if (user == null){
            res.put("status", "fail");
            res.put("data", null);
            res.put("msg", "用户名错误");
            return JSONObject.toJSONString(res);
        }
        if (!user.getPassword().equals(password)){
            res.put("status", "fail");
            res.put("data", null);
            res.put("msg", "密码错误");
            return JSONObject.toJSONString(res);
        }
        Cookie cookieUsername = new Cookie("username",user.getUsername());
        Cookie cookieRole = new Cookie("role",user.getRole());
        response.addCookie(cookieUsername);
        response.addCookie(cookieRole);

        data.put("role",user.getRole());
        data.put("username",user.getUsername());
        data.put("name",user.getName());
        data.put("graphs",user.getGraphs());

        res.put("status", "success");
        res.put("data", data);
        res.put("msg", "登录成功");

        return JSONObject.toJSONString(res);
    }

}
